package com.david.cloud.code.service.impl;

import cn.hutool.core.util.RandomUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.david.cloud.code.entity.AuthCode;
import com.david.cloud.code.service.IAuthCodeService;
import com.david.cloud.service.CodeService;
import com.david.cloud.service.MailService;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.Reference;
import org.apache.dubbo.config.annotation.Service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;

@Slf4j
@Service
@Component
public class CodeServiceImpl implements CodeService {
    @Reference
    private MailService mailService;
    @Autowired
    private IAuthCodeService authCodeService;

    @Override
    @Transactional
    public Boolean create(String email) {
        AuthCode authCode = new AuthCode();
        String code = RandomUtil.randomString(4);
        LocalDateTime now = LocalDateTime.now();
        LocalDateTime expire = now.plusMinutes(5);
        authCode.setCode(code);
        authCode.setEmail(email);
        authCode.setCreatetime(now);
        authCode.setExpiretime(expire);
        boolean save = authCodeService.save(authCode);
        boolean send = mailService.send(email, code);
        return save && send;
    }

    @Override
    public Integer validate(String email, String code) {
        LambdaQueryWrapper<AuthCode> wrapper = Wrappers.<AuthCode>lambdaQuery()
                .eq(AuthCode::getEmail, email)
                .eq(AuthCode::getCode, code)
                .ge(AuthCode::getExpiretime, LocalDateTime.now());
        int count = authCodeService.count(wrapper);
        return count > 0 ? 0 : 1;
    }
}
